package com.ruoyi.web.controller.order;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OConvertUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.order.domain.ProductImportData;
import com.ruoyi.order.domain.ProductImportResult;
import com.ruoyi.order.service.ITbProductTypeService;
import com.ruoyi.order.service.ITbProductWholesaleService;
import com.ruoyi.order.vo.ProductPlusVo;
import org.apache.poi.ss.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.order.domain.TbProduct;
import com.ruoyi.order.service.ITbProductService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商品Controller
 * 
 * @author ruoyi
 * @date 2025-08-19
 */
@RestController
@RequestMapping("/product/product")
public class TbProductController extends BaseController
{
    @Autowired
    private ITbProductService tbProductService;
    @Autowired
    private ITbProductWholesaleService tbProductWholesaleService;

    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('product:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbProduct tbProduct)
    {
        startPage();
        List<TbProduct> list = tbProductService.selectTbProductList(tbProduct);
        return getDataTable(list);
    }



    /**
     * 查询商品列表--完整版
     */
    @GetMapping("/plusList")
    public TableDataInfo plusList(ProductPlusVo productPlusVo)
    {
        Long productTypeId = productPlusVo.getProductTypeId();
        if (OConvertUtils.isEmpty(productTypeId)){
            throw new ServiceException("请选择商品类型");
        }
        startPage();
        // 根据商品类型返回一个动态参数 的列表
        List<JSONObject> list = tbProductService.selectProductVoList(productPlusVo);
        return getDataTable(list);
    }

    /**
     * 查询商品类型动态列
     * @param productPlusVo
     * @return
     */
    @GetMapping("/plusListCloumn")
    public AjaxResult plusListCloumn(ProductPlusVo productPlusVo)
    {
        Long productTypeId = productPlusVo.getProductTypeId();
        if (OConvertUtils.isEmpty(productTypeId)){
            throw new ServiceException("请选择商品类型");
        }
        // 根据商品类型返回一个动态参数 的列表
        List<String> cloumns = tbProductWholesaleService.selectTypeCloumn(productTypeId);
        return AjaxResult.success(cloumns);
    }

    /**
     *  添加
     */
    @PostMapping("/addProduct")
    public AjaxResult addProduct(@RequestBody JSONObject jsonObject)
    {
        tbProductService.addProductVo(jsonObject);
        return AjaxResult.success();
    }
    /**
     *  添加
     */
    @PostMapping("/editProduct")
    public AjaxResult editProduct(@RequestBody JSONObject jsonObject)
    {
        tbProductService.editProduct(jsonObject);
        return AjaxResult.success();
    }
    /**
     *  添加
     */
    @PostMapping("/removeProduct")
    public AjaxResult removeProduct(@RequestBody JSONObject jsonObject)
    {
        List<Long> ids = jsonObject.getJSONArray("ids").toJavaList(Long.class);
        tbProductService.removeProducts(ids);
        return AjaxResult.success();
    }


    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('product:product:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbProduct tbProduct)
    {
        List<TbProduct> list = tbProductService.selectTbProductList(tbProduct);
        ExcelUtil<TbProduct> util = new ExcelUtil<TbProduct>(TbProduct.class);
        util.exportExcel(response, list, "商品数据");
    }




    /**
     * 获取商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('product:product:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tbProductService.selectTbProductById(id));
    }

    /**
     * 新增商品
     */
    @PreAuthorize("@ss.hasPermi('product:product:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbProduct tbProduct)
    {
        return toAjax(tbProductService.insertTbProduct(tbProduct));
    }

    /**
     * 修改商品
     */
    @PreAuthorize("@ss.hasPermi('product:product:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbProduct tbProduct)
    {
        return toAjax(tbProductService.updateTbProduct(tbProduct));
    }

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('product:product:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tbProductService.deleteTbProductByIds(ids));
    }


    /**
     * 商品导出
     */
    @PostMapping("/exportProducts")
    public void exportProducts(HttpServletResponse response,TbProduct tbProduct) throws URISyntaxException, IOException {
       try{
           Workbook workbook = tbProductService.exportData(response, tbProduct);
           response.setContentType("application/vnd.ms-excel");
           String resultFileName = URLEncoder.encode(DateUtils.dateTime()+"商品列表.xlsx", "UTF-8");
           response.setHeader("Content-disposition", "attachment;filename=" + resultFileName + ";" + "filename*=utf-8''" + resultFileName);
           workbook.write(response.getOutputStream());
           workbook.close();
           response.flushBuffer();
       }catch (Exception e){
           throw new RuntimeException(e);
       }
    }

    @PostMapping("/importProduct")
    public AjaxResult importData(MultipartFile files, boolean updateSupport) throws Exception{
        Map<String, List<List<String>>> result = new HashMap<>();
        try{
            InputStream inputStream = files.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }

                String sheetName = sheet.getSheetName();
                List<List<String>> sheetData = new ArrayList<>();
                // 获取第一行和最后一行的索引
                int firstRowNum = sheet.getFirstRowNum();
                int lastRowNum = sheet.getLastRowNum();

                // 遍历行
                for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }

                    List<String> rowData = new ArrayList<>();
                    int firstCellNum = row.getFirstCellNum();
                    int lastCellNum = row.getLastCellNum();

                    // 遍历单元格
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        rowData.add(getCellValue(cell));
                    }

                    sheetData.add(rowData);
                }
                result.put(sheetName, sheetData);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return AjaxResult.success(result);
    }


    /**
     * 获取单元格的值，处理不同类型的单元格
     */
    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        String cellValue = "";
        switch (cell.getCellType()) {
            case STRING:
                cellValue = cell.getStringCellValue();
                break;
            case NUMERIC:
                // 处理日期类型
                if (DateUtil.isCellDateFormatted(cell)) {
                    cellValue = cell.getDateCellValue().toString();
                } else {
                    // 数字类型，避免科学计数法
                    cellValue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA:
                // 公式类型，获取计算结果
                try {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                } catch (IllegalStateException e) {
                    cellValue = cell.getStringCellValue();
                }
                break;
            default:
                cellValue = "";
        }

        return cellValue.trim();
    }

    @PostMapping("/importProductData")
    public AjaxResult importProductData(MultipartFile file) throws Exception {
        try {
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);

            List<ProductImportResult> results = new ArrayList<>();

            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }
                boolean updateSupport = true;
                ProductImportResult sheetResult = processSheet(sheet, updateSupport);
                results.add(sheetResult);
            }

            workbook.close();
            inputStream.close();

            return AjaxResult.success(results);
        } catch (Exception e) {
            throw new RuntimeException("导入失败: " + e.getMessage(), e);
        }
    }
    @Resource
    private ITbProductTypeService tbProductTypeService;

    private ProductImportResult processSheet(Sheet sheet, boolean updateSupport) {
        ProductImportResult result = new ProductImportResult();

        try {
            // 跳过第一行标题，从第二行开始读取表头
            Row row0 = sheet.getRow(0);
            String productType =row0.getCell(0).getStringCellValue();;
            Row headerRow = sheet.getRow(1);
            if (headerRow == null) {
                result.setErrorMessage("表头行不存在");
                return result;
            }

            // 解析表头，获取固定列和动态列
            List<String> headers = parseHeaders(headerRow);
            List<String> dynamicColumns = getDynamicColumns(headers);

            // 处理数据行
            List<ProductImportData> productList = new ArrayList<>();
            int lastRowNum = sheet.getLastRowNum();

            for (int rowNum = 2; rowNum <= lastRowNum; rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null || isRowEmpty(row)) {
                    continue;
                }

                ProductImportData product = parseProductRow(row, headers, dynamicColumns);
                if (product != null) {
                    productList.add(product);
                }
            }

            // 保存数据
            int successCount = tbProductService.importProductData(productList, productType, updateSupport);
            result.setSheetName(productType);
            result.setSuccessCount(successCount);
            result.setTotalCount(productList.size());
        } catch (Exception e) {
            result.setErrorMessage("处理Sheet失败: " + e.getMessage());
        }

        return result;
    }

    private List<String> parseHeaders(Row headerRow) {
        List<String> headers = new ArrayList<>();
        int lastCellNum = headerRow.getLastCellNum();

        for (int cellNum = 0; cellNum < lastCellNum; cellNum++) {
            Cell cell = headerRow.getCell(cellNum);
            String headerValue = getCellValue(cell);
            headers.add(headerValue);
        }

        return headers;
    }

    private List<String> getDynamicColumns(List<String> headers) {
        // 固定列：商品编号、商品名称、商品类别、商品规格、商品链接、商品单价
        List<String> fixedColumns = Arrays.asList("商品编号", "商品名称", "商品类别", "商品规格", "商品链接", "商品单价");

        return headers.stream()
                .filter(header -> !fixedColumns.contains(header) && StringUtils.isNotBlank(header))
                .collect(Collectors.toList());
    }

    private ProductImportData parseProductRow(Row row, List<String> headers, List<String> dynamicColumns) {
        try {
            ProductImportData product = new ProductImportData();

            // 解析固定列
            for (int i = 0; i < headers.size() && i < row.getLastCellNum(); i++) {
                String header = headers.get(i);
                String cellValue = getCellValue(row.getCell(i));

                switch (header) {
                    case "商品编号":
                        product.setProductNo(cellValue.toString());
                        break;
                    case "商品名称":
                        product.setProductName(cellValue.toString());
                        break;
                    case "商品类别":
                        product.setProductCategory(cellValue.toString());
                        break;
                    case "商品规格":
                        product.setProductSpecification(cellValue.toString());
                        break;
                    case "商品链接":
                        product.setProductUrl(cellValue.toString());
                        break;
                    case "商品单价":
                        if (StringUtils.isNotBlank(cellValue)) {
                            product.setProductPrice(new BigDecimal(cellValue));
                        }
                        break;
                    default:
                        // 动态列处理
                        if (dynamicColumns.contains(header) && StringUtils.isNotBlank(cellValue)) {
                            product.addWholesalePrice(header, new BigDecimal(cellValue));
                        }
                        break;
                }
            }

            return product;
        } catch (Exception e) {
            return null;
        }
    }

    private boolean isRowEmpty(Row row) {
        if (row == null) {
            return true;
        }

        for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
            Cell cell = row.getCell(cellNum);
            if (cell != null && StringUtils.isNotBlank(getCellValue(cell))) {
                return false;
            }
        }
        return true;
    }
}
